<template>
  <div class="body">
    <ul v-for="(item,index) in value" :key="index" class="el-upload-list el-upload-list--picture-card">
      <li tabindex="0" class="el-upload-list__item is-ready" :style="'width: '+width+'px;height: '+height+'px'">
        <div>
          <img :src="item" alt="" class="el-upload-list__item-thumbnail">
          <span class="el-upload-list__item-actions">
            <span v-if="index != 0" class="el-upload-list__item-preview" @click="moveMaterial(index,'up')">
              <i class="el-icon-back" />
            </span>
            <span class="el-upload-list__item-preview" @click="zoomMaterial(index)">
              <i class="el-icon-view" />
            </span>
            <span class="el-upload-list__item-delete" @click="deleteMaterial(index)">
              <i class="el-icon-delete" />
            </span>
            <span v-if="index != value.length-1" class="el-upload-list__item-preview" @click="moveMaterial(index,'down')">
              <i class="el-icon-right" />
            </span>
          </span>
        </div>
      </li>
    </ul>
    <div v-show="value.length<picNum" class="uploadIcon" :style="'width:'+width+'px;height:'+height+'px'" @click="dialogVisible=true">
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </div>

    <el-dialog
      append-to-body
      :visible.sync="previewDisplay"
      width="35%"
    >
      <img :src="url" alt="" style="width: 100%">
    </el-dialog>

    <el-dialog
      title="图片素材库"
      :visible.sync="dialogVisible"
      width="70%"
      @open="init()"
      append-to-body
    >
      <el-container>
        <el-aside width="unset">
          <div style="margin-bottom: 10px">
            <el-button
              class="el-icon-plus"
              size="small"
              @click="addGropu()"
            >
              添加分组
            </el-button>
          </div>
          <el-tabs v-model="materialgroupObjId" v-loading="" tab-position="left" @tab-click="tabClick">
            <el-tab-pane
              v-for="(item,index) in materialgroupList"
              :key="item.id"
              :name="item.id"
            >
              <span slot="label"> {{ item.name }}</span>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        <el-main>
          <el-card>
            <div slot="header">
              <el-row>
                <el-col :span="12">
                  <span>{{ materialgroupObj.name }}</span>
                  <span v-if="materialgroupObj.id != '-1'">
                    <el-button size="small" type="text" class="el-icon-edit" style="margin-left: 10px;" @click="reName">重命名</el-button>
                    <el-button size="small" type="text" class="el-icon-delete" style="margin-left: 10px;color: red" @click="deleteGroup">删除</el-button>
                  </span>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-upload
                    :action="uploadFileUrl"
                    :headers="headers"
                    :file-list="[]"
                    :data="{groupId:materialgroupObjId}"
                    multiple
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                  >

                    <el-button size="small" type="primary">批量上传</el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </div>
            <div v-loading="tableLoading">
              <el-alert
                v-if="tableData.length <= 0"
                title="暂无数据"
                type="info"
                :closable="false"
                center
                show-icon
              />
            </div>
            <el-row :gutter="5">
              <!--批量删除复选框-->
              <el-checkbox-group v-model="urls" :max="picNum-value.length">
                <el-col v-for="(item,index) in tableData" :key="index" :span="4">
                  <el-card :body-style="{ padding: '5px' }">
                    <el-image
                      style="width: 100%;height: 100px"
                      :src="item.url"
                      fit="contain"
                      :preview-src-list="[item.url]"
                      :z-index="9999"
                    />
                    <div>
                      <el-checkbox class="material-name" :label="item.url">
                        选择
                      </el-checkbox>
                      <el-row>
                        <el-col :span="24" class="col-do">
                          <el-button type="text" size="medium" @click="deleteImage(item.id)">删除</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </el-card>
                </el-col>
              </el-checkbox-group>
            </el-row>
          </el-card>
          <el-pagination
            :current-page.sync="page.pageNum"
            :page-sizes="[12, 24]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            class="pagination"
            @size-change="sizeChange"
            @current-change="pageChange"/>
        </el-main>
      </el-container>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureUrls">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as groupApi from '@/api/shop/group'
import * as materialApi from '@/api/shop/material'
import {mapGetters} from 'vuex'
import {getToken} from "@/utils/auth"

export default {
  name: "PictureManager",
  props: {
    value: {
      type: Array,
      require
    },
    width: {
      type: String,
      require
    },
    height: {
      type: String,
      require
    },
    picNum:{
      type:Number,
      default:1
    }
  },
  data() {
    return {
      images: [],
      materialgroupList: [],
      materialgroupObj: {
        name: '全部分类',
        id: '-1'
      },
      tableData: [],
      urls: [],
      page: {
        total: 0, // 总页数
        pageNum: 1, // 当前页数
        pageSize: 12, // 每页显示多少条
        ascs: [], // 升序字段
        descs: 'create_time'// 降序字段
      },
      dialogVisible: false,
      materialgroupObjId: '-1',
      tableLoading: false,
      headers: {Authorization: 'Bearer ' + getToken()},
      resultNumber: 0,
      previewDisplay:false,
      url:''
    }
  },
  computed: {
    ...mapGetters([
      'uploadFileUrl'
    ])
  },
  methods: {
    init() {
      this.getPage();
      this.getGroupList();
    },
    moveMaterial(index, type) {
      if (type == 'up') {
        const tempOption = this.value[index - 1]
        this.$set(this.value, index - 1, this.value[index])
        this.$set(this.value, index, tempOption)
      }
      if (type == 'down') {
        const tempOption = this.value[index + 1]
        this.$set(this.value, index + 1, this.value[index])
        this.$set(this.value, index, tempOption)
      }
    },
    zoomMaterial(index) {
      this.previewDisplay = true
      this.url = this.value[index]
    },
    deleteMaterial(index) {
      const that = this
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.value.splice(index, 1)
        that.urls = []
      })
    },
    toSeleteMaterial() {
      this.listDialogVisible = true
      if (this.tableData.length <= 0) {
        this.materialgroupPage()
      }
    },
    getGroupList() {
      //获得分组列表
      groupApi.listGroup().then((res) => {
        res.data.unshift({
          id: '-1',
          name: '全部分组'
        });
        this.materialgroupList = res.data;
      });
    },
    sizeChange(val) {
      this.page.pageNum = 1
      this.page.pageSize = val
      this.getPage()
    },
    pageChange(val) {
      this.page.pageNum = val
      this.getPage()
    },
    handleClose() {

    },
    tabClick(tab, event) {
      this.urls = []
      const index = Number(tab.index)
      const materialgroupObj = this.materialgroupList[index]
      materialgroupObj.index = index
      this.materialgroupObj = materialgroupObj
      this.materialgroupObjId = materialgroupObj.id
      this.page.pageNum = 1
      this.getPage()
    },
    getPage() {
      materialApi.listMaterial({
        groupId: this.materialgroupObjId,
        ...this.page
      }).then((res) => {
        this.page.total = res.total;
        this.tableData = res.rows;
      })
    },
    deleteImage(id) {
      let that = this;
      this.$confirm('是否确认删除该素材？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        materialApi.remove(id).then(function () {
          that.getPage()
        })
      })
    },
    addGropu() {
      const that = this;
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        let resList=this.materialgroupList.filter((item)=>{
          return item.name===value;
        });
        if(resList.length>0){
          this.$message({
            showClose: true,
            message: '分类重名',
            type: 'warning'
          });
          return;
        };
        groupApi.addGroup({
          name: value
        }).then(() => {
          that.getGroupList();
        })
      }).catch(() => {

      })
    },
    deleteGroup() {
      let that = this;
      this.$confirm('是否确认删除该分组？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        groupApi.remove(that.materialgroupObjId).then(function () {
          that.materialgroupObjId = '-1';
          that.page.pageNum = 1;
          that.materialgroupObj = that.materialgroupList[0];
          that.getPage();
          that.getGroupList();
        })
      })
    },
    reName() {
      const that = this
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: that.materialgroupObj.name
      }).then(({value}) => {
        groupApi.updateGroup({
          id: that.materialgroupObj.id,
          name: value
        }).then(function () {
          that.materialgroupObj.name = value;
          that.$set(that.materialgroupList, that.materialgroupObj.index, that.materialgroupObj);
        })
      }).catch(() => {

      })
    },
    beforeUpload(file) {
      const isPic =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG、GIF 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    handleSuccess(response, file, fileList) {
      const that = this;
      materialApi.addMaterial({
        type: '1',
        groupId: that.materialgroupObjId != '-1' ? that.materialgroupObjId : null,
        name: file.name,
        url: response.data.url
      }).then(() => {
        that.resultNumber++
        console.log(fileList.length + ":" + that.resultNumber);
        if (fileList.length === that.resultNumber) {
          that.page.pageNum = 1;
          that.getPage();
          that.resultNumber = 0;
        }
      })
    },
    sureUrls() {
      this.urls.forEach(item => {
        this.$set(this.value, this.value.length, item)
      })
      this.dialogVisible = false
    }
  }

}
</script>

<style lang="scss" scoped>
.body{
  display: flex;
  flex-direction: row;
}
.uploadIcon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fdfdfd;

  &:hover {
    border: 1px dashed #00afff;
    cursor: pointer
  }
}

.col-do {
  display: flex;
  justify-content: center;
}

</style>
